package com.joe.xl.common.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RSAHelper {
    private final static String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIRn29xKG01x2AnMTjVuRCx0jDN4LQ0DH3HTFEm6+zzDn6IPZk1UFSuHNjCS3n/hbCBNSLvRnPtmMnxEuuuii1ECAwEAAQ==";
    private final static String PRIVATE_KEY = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAhGfb3EobTXHYCcxONW5ELHSMM3gtDQMfcdMUSbr7PMOfog9mTVQVK4c2MJLef+FsIE1Iu9Gc+2YyfES666KLUQIDAQABAkB1x9WiPiHPYGfnP2CK0w295ecZmdupaY+9NyEi/TukLqklpEy/RVOd7HfqSWDfYJAHIXRysj62Mgopf4J/1HnJAiEA5Ou97FX8Es/icAOFpIekPpe0mf6JhLQGOxKF78cPMUMCIQCUEWmS5IgLnjSfbufaGxTcNZY77zK2TvoomM2cC6EN2wIgEWYNcEn0t6VPK35JCQE6LXuwQUgEQa7BDnpQ7bFuaSsCIQCS2j4yMTR5CVy5r76GBAwJZ6BsKw3J4MSdFQf/t0zxtwIhAMsy2OFxoPHm4KVS575XJgbAsBXeRcvGhuEA3Jl/JNyk";

    static {
//        initKey();
    }

    private static void initKey(){
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(512, new SecureRandom());

        // 生成一个密钥对，保存在keyPair中
        KeyPair       keyPair         = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey      = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey  publicKey       = (RSAPublicKey) keyPair.getPublic();  // 得到公钥

        String publicKeyStr = new String(Base64.encodeBase64(publicKey.getEncoded()));

        // 得到私钥字符串
        String privateKeyStr = new String(Base64.encodeBase64((privateKey.getEncoded())));

        System.out.println("publickey--- " + publicKeyStr);
        System.out.println("privatekey--- " + privateKeyStr);
    }


    public static String encrypt( String str) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(PUBLIC_KEY);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));

        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));

        return outStr;
    }

    public static String decrypt(String str) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));

        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(PRIVATE_KEY);

        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));

        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));

        return outStr;
    }

    public static void main(String[] args) {
        String key = "{\"locationType\":\"SC01\",\"deviceId\":\"69\"}";

        String enKey = null;

        String deKey = null;
        try {
            enKey = encrypt(key);
            deKey = decrypt(enKey);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("加密之后 " + enKey);
        System.out.println("解密之后 " + deKey);

    }
}
